package com.battery.web.controller.system.battery;

import java.math.BigDecimal;
import java.util.List;

import com.battery.common.enums.EventStateEnum;
import com.battery.common.utils.DateUtils;
import com.battery.system.domain.BO.EventBO;
import com.battery.system.domain.VO.EventVO;
import com.battery.system.service.ISysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.battery.common.annotation.Log;
import com.battery.common.enums.BusinessType;
import com.battery.system.domain.Event;
import com.battery.system.service.battery.IEventService;
import com.battery.common.core.controller.BaseController;
import com.battery.common.core.domain.AjaxResult;
import com.battery.common.utils.poi.ExcelUtil;
import com.battery.common.core.page.TableDataInfo;

/**
 * 活动Controller
 *
 * @author battery
 * @date 2021-01-26
 */
@Controller
@RequestMapping("/system/event")
public class EventController extends BaseController {
    private String prefix = "system/event";

    @Autowired
    private IEventService eventService;


    @Autowired
    private ISysConfigService sysConfigService;


    @Autowired
    private Sid sid;

    @RequiresPermissions("system:event:view")
    @GetMapping()
    public String event() {
        return prefix + "/event";
    }

    /**
     * 查询活动列表
     */
    @RequiresPermissions("system:event:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(EventBO eventBO) {
        startPage();
        List<EventVO> list = eventService.selectEventVOList(eventBO);
        return getDataTable(list);
    }

    /**
     * 导出活动列表
     */
    @RequiresPermissions("system:event:export")
    @Log(title = "活动", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Event event) {
        List<Event> list = eventService.selectEventList(event);
        ExcelUtil<Event> util = new ExcelUtil<Event>(Event.class);
        return util.exportExcel(list, "event");
    }

    /**
     * 新增活动
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存活动
     */
    @RequiresPermissions("system:event:add")
    @Log(title = "活动", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Event event) {

        if (StringUtils.isBlank(event.getEventName())) {
            return error("请填写活动名称");
        }

        // 校验活动名称是否重复
        Event checkNameEvent = eventService.selectByEventName(event.getEventName());
        if (checkNameEvent != null) {
            return error("活动名称重复，请重新输入！");
        }
        if (StringUtils.isBlank(event.getTitleImg())) {
            return error("请上传活动标题图片");
        }

        if (event.getStartTime() == null) {
            return error("请设置活动开启时间！");
        }

        if (event.getEndTime() == null) {
            return error("请设置活动结束时间");
        }

        if (StringUtils.isBlank(event.getWebContent())) {
            return error("请设置网页内容");
        }

        if (event.getActivateCondition() == null) {
            return error("请填写'激活条件(累计X元订单金额)'!");
        }

        if (event.getActivateCondition().compareTo(BigDecimal.ZERO) <= 0) {
            return error("'激活条件(累计X元订单金额)'不能小于等于0");
        }


        if (event.getEventShare() == null) {
            return error("请填写'活动分润'!");
        }

        if (event.getEventShare().compareTo(BigDecimal.ZERO) <= 0) {
            return error("'活动分润'不能小于等于0");
        }

        event.setId(sid.nextShort());
        String doMain = sysConfigService.selectConfigByKey("sys.event.showWeb");
        event.setWebUrl(doMain + event.getId()); //  保存网页展示内容
        event.setCreatedTime(DateUtils.getNowDate());
        return toAjax(eventService.insertEvent(event));
    }


    /**
     * 展示活动网页内容
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/showWeb/{id}")
    public String showWeb(@PathVariable("id") String id, ModelMap mmap) {
        Event event = eventService.selectEventById(id);
        mmap.put("webContent", event.getWebContent());
        return prefix + "/showWeb";
    }

    /**
     * 修改活动
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        Event event = eventService.selectEventById(id);
        mmap.put("event", event);
        return prefix + "/edit";
    }

    /**
     * 修改保存活动
     */
    @RequiresPermissions("system:event:edit")
    @Log(title = "活动", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Event event) {

        if (StringUtils.isBlank(event.getId())) {
            return error("主键ID为空");
        }

        if (StringUtils.isBlank(event.getEventName())) {
            return error("请填写活动名称");
        }
        // 校验活动名称是否重复
        Event checkNameEvent = eventService.selectByEventName(event.getEventName());
        if (checkNameEvent != null && !checkNameEvent.getId().equals(event.getId())) {
            return error("活动名称重复，请重新输入！");
        }
        if (StringUtils.isBlank(event.getTitleImg())) {
            return error("请上传活动标题图片");
        }

        if (event.getStartTime() == null) {
            return error("请设置活动开启时间！");
        }

        if (event.getEndTime() == null) {
            return error("请设置活动结束时间");
        }

        if (StringUtils.isBlank(event.getWebContent())) {
            return error("请设置网页内容");
        }

        if (event.getEventShare() == null) {
            return error("请填写'活动分润'!");
        }

        if (event.getEventShare().compareTo(BigDecimal.ZERO) <= 0) {
            return error("'活动分润'不能小于等于0");
        }

        event.setUpdatedTime(DateUtils.getNowDate());
        return toAjax(eventService.updateEvent(event));
    }

    /**
     * 删除活动(逻辑)
     */
    @RequiresPermissions("system:event:remove")
    @Log(title = "活动", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        if (StringUtils.isBlank(ids)) {
            return error("ids为空");
        }
        if (ids.contains(",")) {
            return error("暂时不支持批量操作");
        }
        return toAjax(eventService.deleteLogicEventById(ids));
    }


    /**
     * 活动开启或者关闭
     *
     * @param id
     * @param open
     * @return
     */
    @RequiresPermissions("system:event:openOrClose")
    @Log(title = "活动", businessType = BusinessType.UPDATE)
    @PostMapping("/openOrClose")
    @ResponseBody
    public AjaxResult openOrClose(String id, Integer open) {

        return toAjax(eventService.openOrClose(id, open));
    }


    /**
     * 选择活动 用于设备列表
     *
     * @return
     */
    @GetMapping("/choiceEvents")
    public String choiceEvents() {
        return "system/device/choiceEvents";
    }


    /**
     * 查询可选择的活动（
     *  可选择： 1，活动没有结束
     *  2，
     * ）
     *
     * @return
     */
    @PostMapping("/eventlist")
    @ResponseBody
    public TableDataInfo eventlist() {
        startPage();
        List<EventVO> list = eventService.averageEventList();
        return getDataTable(list);
    }

}
